<?php
/**
 * (jobs) 其他备货审批
 */
namespace App\Jobs\Stocking;

use App\Models\Inventory\AreaCn;
use App\Util\SerialNo;
use App\Models\Product\ProductSku;
use App\Models\Stocking\StockingApply;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class SkuOtherApproval implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $skus;

    /**
     * SkuOtherApproval constructor.
     * @param $skus
     */
    public function __construct($skus)
    {
        $this->skus = $skus;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->skus);
    }

    private function exeFillData($skus){
        foreach ($skus as $sku){
            if($sku->approval_num > 0){
                $item = [];
                $item['stocking_no'] = SerialNo::getBhNo();
                $item['area_id'] = $sku->area_id;
                $item['psku_id'] = $sku->psku_id;
                $item['seller_id'] = $sku->seller_id;
                $item['apply_num'] = $sku->approval_num;
                $ps = ProductSku::getMpSkuById($sku->psku_id);
                $itemDetail = [];
                $amount = 0;
                foreach ($ps as $k => $v){
                    $itemDetail[$k]['area_id'] = $sku->area_id;
                    $itemDetail[$k]['psku_id'] = $v['psku_id'];
                    $itemDetail[$k]['apply_detail_num'] = $v['num'] * ($sku->approval_num);
                    $amount += $v['unit_price'] * $itemDetail[$k]['apply_detail_num'];
                }
                $item['amount'] = $amount;
                $stockingApply = StockingApply::query()->create($item); //备货单
                $stockingApply->detail()->createMany($itemDetail); ////备货明细
                $this->_addAreaCn($sku->area_id,$sku->psku_id);
            }
        }
    }

    private function _addAreaCn($areaId,$pSkuId){
        $count = AreaCn::query()
            ->where('area_id', $areaId)
            ->where('psku_id',$pSkuId)
            ->count();
        if($count == 0){
            AreaCn::query()->create(['area_id' => $areaId,'psku_id' => $pSkuId]);
        }
    }

}
